package eerbaar.v2.pattern.client.internal.teach;

import eerbaar.game.IGame;
import eerbaar.persona.IPersona;
import eerbaar.shared.service.ServiceFactory;
import eerbaar.shared.tree.INode;
import eerbaar.shared.tree.NodeCmdFactory;
import eerbaar.v2.app.GameHelper;
import eerbaar.v2.app.mover.IPersonaMover;
import eerbaar.v2.gamebuilder.client.request.Requester;
import eerbaar.v2.pattern.client.internal.request.RequestProcessor2;
import eerbaar.v2.pattern.client.internal.request.RequestType2;

public class TeachingCommandBody {

    private final TeachingMediator mediator;

    public TeachingCommandBody() {
        this.mediator = TeachingMediator.getInstance();
    }

    private void clearPetsHistory() {
        IGame game = GameHelper.getGame();

        IPersona pet = game.getPersona("pet");
        INode node = pet.getHead().getBrain().getMemory().getTimeNode();
        NodeCmdFactory.removeAllChildren(node);
    }

    public boolean isTeaching() {

        return (this.mediator.getState() == TeachingState.TEACHING);
    }

    private void pleaseWait() {
        IPersonaMover mover = ServiceFactory.getService(IPersonaMover.class);
        if (mover != null) {
            mover.pleaseWait();
        }
    }

    private void sit() {
        IPersonaMover mover = ServiceFactory.getService(IPersonaMover.class);
        if (mover != null) {
            mover.sit();
        }
    }

    public void startTeaching() {

        this.mediator.setState(TeachingState.TEACHING);
        clearPetsHistory();
        sit();
    }

    public void stopTeaching() {

        pleaseWait();
        this.mediator.setState(TeachingState.WAITING_FOR_SERVER);

        RequestProcessor2 processor = new RequestProcessor2(this.mediator);
        Requester.getInstance().start(processor, new RequestType2());
    }
}
